<template>
    <div class="addUpdWorkReport">
        <div class="title">发布汇报</div>
        <div class="center">
             <el-form label-position="top" label-width="80px" :rules="rules" :model="formDatas" ref="workReportRef">
                <el-form-item label="收件人" prop="sendUser" >
                    <el-cascader v-model="formDatas.sendUser"  style="width: 50%;" :options="options" :show-all-levels="false" :props="props" clearable></el-cascader>
    				<el-checkbox style="margin-left: 30px;" v-model="formDatas.isNotice">通知提醒</el-checkbox>
                </el-form-item>
                 <el-form-item label="工作内容"  :rules="{ required: true, message: '请输入汇报内容', trigger: 'blur' }">
                    <div style="border: 1px solid #ccc;width: 100%;">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editorRef"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="formDatas.content"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="handleCreated"
                            />
                        </div>
                </el-form-item>
             </el-form>   
             <div class="buttom">
                <el-button class="addButton" @click="addItem" >立即发布</el-button>
             </div>
        </div>
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css';
import useUserStore from '@/store/modules/user';
import { getDeptUser } from '@/api/hkd';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { getToken } from '@/utils/auth';
import { addWorkReport, editWorkReport } from '@/api/workReport';
import mydailyStore from "@/store/modules/mydaily";
import { ElMessage } from 'element-plus';
const route = useRoute();
const router = useRouter();
const store = mydailyStore();
const { proxy } = getCurrentInstance();
const editorRef = shallowRef();
const useStore = useUserStore();
let reportList = computed(() => {
    return store.reportList;
})
console.log(proxy);
let formData = reactive({
    formDatas: {
        sendUser: [],
        content: '',
        userId: '', //用户id
        isNotice: 0
    },
    rules: {
        sendUser: { required: true, message: '请选择收件人', trigger: 'blur' }
    },
    props: { multiple: true, children: 'children', value: 'id', label: 'label', emitPath: false },
    options: [],
     editor: null,
    editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
            uploadImage: {
                server: import.meta.env.VITE_APP_BASE_API + '/common/upload',
                fieldName: 'file',
                metaWithUrl: true,
                headers: {
                    'Authorization': 'Bearer ' + getToken()
                },
                withCredentials: true,
                timeout: 5 * 1000,
                allowedFileTypes: ['image/*'],
                onSuccess(file, res) {
                    console.log(file.name + '上传成功');
                },
                customInsert(res, insertFn) {
                    insertFn(import.meta.env.VITE_APP_BASE_API+res.fileName, '#', '#')
                    console.log(res, insertFn);
                },
                onFailed(file, res) {
                    console.log(file.name + '上传失败');
                }
            }
        }
    },
    mode: 'default',
    toolbarConfig:{}
})
const userId = ref(useStore.userId);
const { formDatas, props, options , editorConfig, mode, editor, toolbarConfig, rules } = toRefs(formData);
const getDeptTree = () => {
    getDeptUser().then(res => {
        if (res.code === 200) {
            options.value = res.data;  
        }
    })
}
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
const isActive = (r) => {
    return r.path === route.path;
}
const getImgSrc = (richtext) => {
    if (richtext.indexOf('src="') != -1) {
        if (richtext.indexOf('http') != -1 || richtext.indexOf('https') != -1) {
            return richtext;
        }
        richtext = richtext.replaceAll('src="', 'src="' + import.meta.env.VITE_APP_BASE_API + '');
    }
    return richtext
}
const toLastView = (visitedViews, view) => {
    const latestView = visitedViews.filter(item => {
        return item.path == '/daily/workReport';
    })
    if (latestView[0]) {
        router.push(latestView[0].fullPath);
    } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        router.replace({ path: view.fullPath });
		router.push({path:'/daily/workReport'})
    }
}
const addItem = () => {
    if (formDatas.value.content) {
        if (formDatas.value.content == '<p><br></p>') {
            ElMessage({ message: '请输入汇报内容', type: 'error', duration: 1 * 1000 })
            return;
        }
    }
    proxy.$refs['workReportRef'].validate((valid) => { 
        if (valid) { 
            formDatas.value.userId = userId.value;
            if (formDatas.value.sendUser.length > 0) {
                formDatas.value.sendUser = formDatas.value.sendUser.join(',');
            }
            if (formDatas.value.content) {
                formDatas.value.content = formDatas.value.content.split(import.meta.env.VITE_APP_BASE_API).join('');
            }
            if (formDatas.value.id) {
                editWorkReport(formDatas.value).then(res => {
                    if (res.code == 200) {
                        proxy.$modal.msgSuccess("修改成功");
                        store.isfbgzhb = true;
                        proxy.$tab.closePage(route).then(({ visitedViews }) => {
                            if (isActive(route)) {
                                toLastView(visitedViews, route);
                            }
                        });
                    }
                });
            } else {
                addWorkReport(formDatas.value).then(res => {
                    if (res.code == 200) {
                        proxy.$modal.msgSuccess("新增成功");
                        store.isfbgzhb = true;
                        proxy.$tab.closePage(route).then(({ visitedViews }) => {
                            if (isActive(route)) {
                                toLastView(visitedViews, route);
                            }
                        });
                    }
                });
            }
           
        }
    })
}
watch(reportList, (newV, oldV) => {
    if (newV.id) {
        formDatas.value = newV;
        if (newV.sendUser && typeof newV.sendUser == 'string') {
            formDatas.value.sendUser = newV.sendUser.split(',');
        }
        formDatas.value.content = getImgSrc(newV.content);
    }
}, { immediate: true })
getDeptTree();
</script>
<style lang="scss" scoped>
$fontSize:14px;
$color:#BE1A21;
$display:flex;
$alignItems:center;
$justifyContent:center;
.addUpdWorkReport{
    width: 100%;
    height: 100%;
    background-color: #FFF;
    padding:  56px 72px;
    .title{
        width: 159px;
        height: 32px;
        background:url('../../assets/images/spbj.png') center center no-repeat;
        background-size: 100% auto;
        color: $color;
        display: $display;
        align-items: $alignItems;
        padding-left: 10px;
    }
    .center{
        width: 100%;
        height: 90%;
        margin-top: 40px;
        .buttom{
            width: 100%;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            .addButton{
               background: $color;
                border-color: $color;
                color:#ffffff;
            }
        }
    }
}
</style>